//
//  UploaderOperation.swift
//  Pods
//
//  Created by CHENZHEN on 15/11/17.
//
//

import UIKit

class UploaderOperation: NSObject {
    
    internal var  remote_url:String = ""
    internal var params = {}
    
    func start(){
        
    }
    
    class func postImage(server strUrl:String,para params:NSDictionary,image images:NSDictionary) -> NSString {
        
        let TWITTERFON_FORM_BOUNDARY = "AaB03x"
        
        let url = NSURL(string: strUrl)
        
        let request =  NSMutableURLRequest(URL: url!)
        
        let MPboundary: String = NSString(format: "--%@",TWITTERFON_FORM_BOUNDARY) as String
        //结束符 AaB03x--
        let endMPboundary: String = NSString(format: "%@--",MPboundary)
            as String
        let body: NSMutableString = NSMutableString()
        //参数的集合的所有key的集合
        var keys: Array = params.allKeys
        
        for(var i:Int = 0;i<keys.count;i++){
            let key = keys[i] as! String;
            body.appendFormat("%@\r\n", MPboundary)
            body.appendFormat("Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key)
            let value = params[key] as! String
            body.appendFormat("%@\r\n", value)
        }
        let myRequestData: NSMutableData = NSMutableData()
        //将body字符串转化为UTF8格式的二进制
        
        myRequestData.appendData(body.dataUsingEncoding(NSUTF8StringEncoding)!)
        
        images.enumerateKeysAndObjectsUsingBlock { (key, obj, stop) -> Void in
            if obj is UIImage{
                
                let imabody:NSMutableString = NSMutableString()
                
                imabody.appendFormat("%@\r\n", MPboundary)
                imabody.appendFormat("Content-Dispostion: form-data;name=\"%@\";filename=\"%@.jpg\"\r\n", key as! NSString,key as! NSString)
                imabody.appendFormat("Content-Type : image/png; charset=utf-8\r\n\r\n")
                
                myRequestData.appendData(imabody.dataUsingEncoding(NSUTF8StringEncoding)!)
                myRequestData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
            }
        };
        
        let end = endMPboundary.stringByAppendingString("\r\n")
        myRequestData.appendData(end.dataUsingEncoding(NSUTF8StringEncoding)!)
        let content: String = NSString(format: "multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY) as String
        
        request.setValue(content, forHTTPHeaderField: "Content-Type")
        
        request.setValue(NSString(format: "%d",myRequestData.length) as String, forHTTPHeaderField: "Content-Length")
        
        request.HTTPBody = myRequestData
        request.HTTPMethod = "post"
        
        let data2:NSData  = try! NSURLConnection.sendSynchronousRequest(request, returningResponse: nil) as NSData
        
        let res:NSString = NSString(data: data2, encoding: NSUTF8StringEncoding)!
        
        return res
    }
    
    class func uploadImage(server:String,params:NSDictionary,images:NSDictionary,complete:(NSDictionary?)->Void){
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            let responseString:NSString = self.postImage(server: server, para: params, image: images) as NSString
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                
                let data:NSData = responseString.dataUsingEncoding(NSUTF8StringEncoding)!
                let dictionary = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as! NSDictionary
                complete(dictionary)
                
            })
        }
    }
    
}
